package cn.deepmax.anime.web.task;

import cn.deepmax.anime.web.Constant;
import cn.deepmax.anime.web.pojo.Section;
import cn.deepmax.anime.web.redis.RedisTemplate;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Slf4j
public class SectionTask {

    public static String URL = Constant.INDEX_URL;


    public List<Section> getSection(){
        List<Section> sections = doGetSection();
        createFolder(sections);
        sections.sort(Comparator.comparingInt(Section::getIndex).reversed());
        return sections;
    }


    private void createFolder(List<Section> list){
        list.forEach(s->{
            String f = String.format("%04d", s.getIndex());
            File file = new File(Constant.getRootFolder()+File.separator + f);
            if(!file.exists()){
                log.info("create dir for section {}",file.getAbsolutePath());
                file.mkdirs();
            }
        });
    }

    private List<Section> doGetSection()  {
        RedisTemplate template = new RedisTemplate();
        List<Section> sections = getSectionFromRemote();
        OptionalInt maxOpt = sections.stream().mapToInt(Section::getIndex).max();
        int max = maxOpt.getAsInt();
        Integer oldMax = template.get(Constant.getMaxKey(),Integer.class);
        if(oldMax==null||oldMax<max){
            if(oldMax==null){
                log.info("Start new pull, size = {}.", max);
            }else{
                log.info("New section found old is {} ,new is {}!",oldMax,max);
            }
            List<Section> newSections = (oldMax==null) ? sections:
                    sections.stream().filter(s -> s.getIndex() > oldMax)
                    .collect(Collectors.toList());
            newSections.forEach(s->{
                template.set(Constant.getSectionKey(s.getIndex()), s);
            });
            template.set(Constant.getMaxKey(), max);
        }
        if(oldMax==null){
            return sections;
        }else{
            return IntStream.range(1, max+1)
                    .mapToObj(index->{
                        Section section = template.get(Constant.getSectionKey(index), Section.class);
                        return section;
                    }).filter(Objects::nonNull)
                    .collect(Collectors.toList());
        }
    }


    private List<Section> getSectionFromRemote()  {
        Document document = getDocument(URL);
        if(document==null){
            return Collections.emptyList();
        }
        Elements sections = document.select("#play_0 ul li a");
        List<Section> s = new ArrayList<>();
        for(Element e:sections){
            String url = Constant.WEB + e.attr("href");
            String id = e.attr("title");
            Integer i = Integer.valueOf(id);
            s.add(new Section(url, i));
        }
        return s;
    }


    public static Document getDocument(String url) {
        Document document = null;
        try {
            document = Jsoup.connect(url)
                    .timeout(3000)
                    .userAgent(Constant.USER_AGENT)
                    .get();
            return document;
        } catch (IOException e) {
            return null;
        }

    }
}
